// player.js - 播放页面逻辑

document.addEventListener('DOMContentLoaded', async () => {
  const isExt = typeof chrome !== 'undefined' && chrome && chrome.runtime && typeof chrome.runtime.sendMessage === 'function';
  // 生成 header logo（固定：优先读取缓存，没有则生成一次后缓存）
  try {
    const headerLogo = document.getElementById('header-logo');
    const draw = (dataUrl) => {
      if (!dataUrl) return;
      const img = new Image();
      img.onload = () => {
        const ctx = headerLogo.getContext('2d');
        ctx.drawImage(img, 0, 0);
      };
      img.src = dataUrl;
    };
    if (isExt && chrome && chrome.storage) {
      const { headerLogoDataUrl } = await chrome.storage.local.get(['headerLogoDataUrl']);
      if (headerLogoDataUrl) {
        draw(headerLogoDataUrl);
      } else {
        const dataUrl = (window.logoGenerator && window.logoGenerator.generateLogo)
          ? window.logoGenerator.generateLogo(40)
          : '';
        draw(dataUrl);
        if (dataUrl) await chrome.storage.local.set({ headerLogoDataUrl: dataUrl });
      }
    } else {
      const dataUrl = (window.logoGenerator && window.logoGenerator.generateLogo)
        ? window.logoGenerator.generateLogo(40)
        : '';
      draw(dataUrl);
    }
  } catch (_) { /* 忽略 logo 生成错误 */ }

  const loadingOverlay = document.getElementById('loading-overlay');
  const mainContainer = document.getElementById('main-container');
  const unlockPrompt = document.getElementById('unlock-prompt');
  const refreshBtn = document.getElementById('refresh-btn');
  const openPopupBtn = document.getElementById('open-popup-btn');

  const searchForm = document.getElementById('search-form');
  const searchInput = document.getElementById('search-input');
  const listContainer = document.getElementById('list-container');
  const listLoading = document.getElementById('list-loading');
  const listError = document.getElementById('list-error');
  const resultList = document.getElementById('result-list');
  const audio = document.getElementById('audio');
  const nowPlaying = document.getElementById('now-playing');
  const playerBar = document.getElementById('player-bar');

  // 分页状态
  let currentKeyword = '';
  let currentPage = 0;
  const pageSize = 30;
  let isLoading = false;
  let hasMore = true;
  // 翻页不使用骨架屏
  let loadingFooterEl = null;

  // 检查解锁状态（扩展环境下才执行）
  if (isExt) {
    const result = await chrome.storage.local.get(['unlockCode', 'unlockTime', 'isUnlocked']);
    let unlocked = false;
    if (result.isUnlocked && result.unlockTime) {
      const unlockTime = result.unlockTime;
      const elapsed = Date.now() - unlockTime;
      const remaining = 12 * 60 * 60 * 1000 - elapsed;
      unlocked = remaining > 0;
    }
    if (!unlocked) {
      // 通过后台再确认一次
      try {
        const bgRes = await new Promise((resolve) => chrome.runtime.sendMessage({ type: 'checkUnlock' }, resolve));
        if (bgRes && bgRes.isUnlocked && bgRes.remaining > 0) {
          unlocked = true;
        }
      } catch (_) {}
    }
    if (unlocked) {
      showPlayer();
    } else {
      showUnlockPrompt();
      if (result.unlockTime) {
        chrome.storage.local.remove(['unlockCode', 'unlockTime', 'isUnlocked']);
      }
    }
  } else {
    // 非扩展环境，避免报错：直接显示主界面
    showPlayer();
  }

  // 刷新按钮 -> 清空搜索与列表
  refreshBtn.addEventListener('click', () => {
    searchInput.value = '';
    renderEmpty();
  });

  // 打开插件按钮
  openPopupBtn.addEventListener('click', () => {
    if (isExt) {
      try {
        chrome.runtime.openOptionsPage ? chrome.runtime.openOptionsPage() : chrome.action.openPopup();
      } catch (_) {}
    }
  });

  function showPlayer() {
    unlockPrompt.classList.add('hidden');
    mainContainer.classList.remove('hidden');
    loadingOverlay.classList.add('hidden');
  }

  function showUnlockPrompt(message) {
    // 需求调整：解锁提示始终隐藏，主界面保持可见
    mainContainer.classList.remove('hidden');
    unlockPrompt.classList.add('hidden');
    loadingOverlay.classList.add('hidden');
  }

  // 搜索事件
  searchForm && searchForm.addEventListener('submit', (e) => {
    e.preventDefault();
    const keyword = searchInput.value.trim();
    if (!keyword) {
      resetPaging();
      renderEmpty();
      return;
    }
    startSearch(keyword);
  });

  // 滚动到底部自动加载下一页
  listContainer && listContainer.addEventListener('scroll', () => {
    if (!currentKeyword || isLoading || !hasMore) return;
    const threshold = 120; // px
    const reachedBottom = listContainer.scrollTop + listContainer.clientHeight >= listContainer.scrollHeight - threshold;
    if (reachedBottom) {
      loadNextPage();
    }
  });

  function renderEmpty() {
    listContainer.classList.remove('hidden');
    listContainer.classList.add('empty');
    resultList.innerHTML = '';
    listError.classList.add('hidden');
    listLoading.classList.add('hidden');
  }

  // 首次加载：清空并显示骨架屏
  function renderLoadingFirst() {
    listContainer.classList.remove('hidden');
    listContainer.classList.remove('empty');
    resultList.innerHTML = '';
    listError.classList.add('hidden');
    listLoading.classList.add('hidden');
    renderSkeletonList(8);
  }

  // 追加加载：不清空，显示底部加载提示
  function showLoadingMore() {
    listContainer.classList.remove('hidden');
    listError.classList.add('hidden');
    // 在结果列表底部插入一个加载占位项（转圈）
    if (!loadingFooterEl) {
      loadingFooterEl = document.createElement('li');
      loadingFooterEl.className = 'loading-footer';
      loadingFooterEl.textContent = '加载中...';
      resultList.appendChild(loadingFooterEl);
    }
  }

  function hideLoadingMore() {
    if (loadingFooterEl && loadingFooterEl.parentNode) {
      loadingFooterEl.parentNode.removeChild(loadingFooterEl);
    }
    loadingFooterEl = null;
    listLoading.classList.add('hidden');
  }

  function renderError() {
    listContainer.classList.remove('hidden');
    listContainer.classList.remove('empty');
    resultList.innerHTML = '';
    listLoading.classList.add('hidden');
    listError.classList.remove('hidden');
  }

  function renderResults(items) {
    listContainer.classList.remove('hidden');
    listContainer.classList.remove('empty');
    listLoading.classList.add('hidden');
    listError.classList.add('hidden');
    // 首次页返回时，清除骨架
    if (currentPage === 0) {
      resultList.innerHTML = '';
    }
    if (!items || items.length === 0) {
      // 无结果也显示空态背景水印
      listContainer.classList.add('empty');
      return;
    }
    // 追加渲染
    for (const item of items) {
      const li = document.createElement('li');
      li.className = 'result-item';
      li.innerHTML = `
        <div class="result-meta">
          <div class="title">${escapeHtml(item.title || '未知标题')}</div>
          <div class="subtitle">${escapeHtml(item.artist || '')}${item.album ? ' · ' + escapeHtml(item.album) : ''}</div>
        </div>
        <div class="duration">${item.duration || ''}</div>
      `;

      const coverUrl = (item.cover && String(item.cover).trim()) ? String(item.cover).trim() : '';
      let coverEl;
      if (coverUrl) {
        const img = document.createElement('img');
        img.className = 'result-cover';
        img.src = coverUrl;
        img.addEventListener('error', () => {
          const ph = document.createElement('div');
          ph.className = 'result-cover no-cover';
          img.replaceWith(ph);
        });
        coverEl = img;
      } else {
        const ph = document.createElement('div');
        ph.className = 'result-cover no-cover';
        coverEl = ph;
      }
      li.insertBefore(coverEl, li.firstChild);

      li.addEventListener('click', () => playItem(item));
      resultList.appendChild(li);
    }
  }

  function escapeHtml(str) {
    return String(str).replace(/[&<>"]/g, (s) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[s]));
  }

  // 无封面占位由 CSS 控制（.result-cover.no-cover），不走任何网络请求

  function playItem(item) {
    if (playerBar) playerBar.classList.remove('hidden');
    nowPlaying.textContent = `${item.title || '未知标题'}${item.artist ? ' - ' + item.artist : ''}`;
    audio.pause();
    audio.removeAttribute('src');
    if (item.url) {
      audio.src = item.url;
      audio.play().catch(handleAudioError);
      return;
    }
    if (!isExt) {
      handleAudioError();
      return;
    }
    chrome.runtime.sendMessage({ type: 'resolveStream', detailUrl: item.detailUrl, id: item.id, platform: item.platform }, (res) => {
      if (!res || !res.ok || !res.url) {
        if (res && res.error === 'needUnlock') {
          showUnlockPrompt('解锁码错误，请重新输入');
          try { chrome.action && chrome.action.openPopup && chrome.action.openPopup(); } catch (_) {}
        } else {
          renderError();
        }
        return;
      }
      audio.src = res.url;
      audio.play().catch(handleAudioError);
    });
  }

  // 统一处理播放失败（例如远端返回 410 Gone 导致媒体加载失败）
  function handleAudioError() {
    try { audio.pause(); } catch (_) {}
    nowPlaying.textContent = '播放失败，可能因为版权原因无法播放，请换一首歌播放';
  }

  // 捕获 <audio> 自身的错误事件（网络错误/解码错误等）
  audio.addEventListener('error', handleAudioError);

  function startSearch(keyword) {
    resetPaging();
    currentKeyword = keyword;
    resultList.innerHTML = '';
    loadNextPage();
  }

  function loadNextPage() {
    if (!currentKeyword || isLoading || !hasMore) return;
    isLoading = true;
    const nextPage = currentPage + 1;
    // 首次加载与追加加载使用不同的加载指示
    if (nextPage === 1) {
      renderLoadingFirst();
    } else {
      showLoadingMore();
    }
    if (!isExt) {
      renderError();
      isLoading = false;
      return;
    }
    chrome.runtime.sendMessage({ type: 'searchTracks', keyword: currentKeyword, page: nextPage, size: pageSize }, (res) => {
      isLoading = false;
      if (!res || !res.ok) {
        hideLoadingMore();
        renderError();
        return;
      }
      const items = res.items || [];
      if (items.length === 0 && nextPage === 1) {
        hideLoadingMore();
        resultList.innerHTML = '';
        renderResults([]);
        hasMore = false;
        return;
      }
      renderResults(items);
      hideLoadingMore();
      currentPage = nextPage;
      hasMore = items.length >= pageSize; // 少于一页则没有更多
    });
  }

  function renderSkeletonList(count) {
    const n = Math.max(1, Math.min(12, count | 0));
    for (let i = 0; i < n; i++) {
      const li = createSkeletonItem();
      resultList.appendChild(li);
    }
  }

  function createSkeletonItem() {
    const li = document.createElement('li');
    li.className = 'skeleton-item';
    const cover = document.createElement('div');
    cover.className = 'skeleton-cover';
    const lines = document.createElement('div');
    lines.className = 'skeleton-lines';
    const l1 = document.createElement('div');
    l1.className = 'skeleton-line';
    const l2 = document.createElement('div');
    l2.className = 'skeleton-line short';
    lines.appendChild(l1);
    lines.appendChild(l2);
    const right = document.createElement('div');
    right.className = 'skeleton-line short';
    li.appendChild(cover);
    li.appendChild(lines);
    li.appendChild(right);
    return li;
  }

  function resetPaging() {
    currentKeyword = '';
    currentPage = 0;
    isLoading = false;
    hasMore = true;
  }

  // 监听 storage 变化
  if (isExt && chrome && chrome.storage) {
    chrome.storage.onChanged.addListener((changes, namespace) => {
      if (namespace === 'local' && changes.isUnlocked) {
        if (changes.isUnlocked.newValue) {
          showPlayer();
        } else {
          showUnlockPrompt();
        }
      }
    });
  }
  // 安全兜底：无论何种状态，初始化结束后隐藏加载层
  try { /* no-op */ } finally {
    loadingOverlay.classList.add('hidden');
  }
});

